/*
 * @Author: ZhanXie
 * @Date: 2020-02-02 20:52:52
 * @LastEditors: ZhanXie
 * @LastEditTime: 2020-03-16 17:43:25
 * @Description: 工具函数
 * @FilePath: /projectStudy/ts-axios/src/helpers/util.ts
 */
const toString = Object.prototype.toString

/**
 * 是否是 Date 类型
 * @param val
 */
export function isDate(val: any): val is Date {
  return toString.call(val) === '[object Date]'
}

/**
 * 是否是 复杂 数据类型
 * @param val
 */
export function isObject(val: any): val is Object {
  return val !== null && typeof val === 'object'
}

/**
 * 是否是 Object 类型
 * @param val
 */
export function isPlainObject(val: any): val is Object {
  return toString.call(val) === '[object Object]'
}

/**
 * 是否是 FormData 类型
 * @param val
 */
export function isFormData(val: any): Boolean {
  return typeof val !== 'undefined' && val instanceof FormData
}

/**
 * 是否是 URLSearchParams 类型
 * @param val
 */
export function isURLSearchParams(val: any): val is URLSearchParams {
  return typeof val !== 'undefined' && val instanceof URLSearchParams
}

/**
 * 把 `from` 里的属性都扩展到 `to` 中，包括原型上的属性
 * @param to
 * @param from
 */
export function extend<T, U>(to: T, from: U): T & U {
  for (const key in from) {
    ;(to as T & U)[key] = from[key] as any
  }
  return to as T & U
}

/**
 * 深拷贝
 * @param obj 要进行深拷贝数据
 */
export function deepMerge(...objs: any[]): any {
  const result = Object.create(null)

  objs.forEach(obj => {
    Object.keys(obj).forEach(key => {
      const val = obj[key]
      if (isPlainObject(key)) {
        if (isPlainObject(result[key])) {
          result[key] = deepMerge(result[key], val)
        } else {
          result[key] = deepMerge({}, val)
        }
      } else {
        result[key] = val
      }
    })
  })
  return result
}
